package controllers;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;

import cn.org.rapid_framework.page.Page;
import controllers.image.ImageAction;
import models.model.Commoditys;
import models.model.Introduces;
import models.model.MloneLevel;
import models.model.MltwoLevel;
import models.model.News;
import models.model.Users;
import models.service.CommoditysService;
import models.service.IntroducesService;
import models.service.MloneLevelService;
import models.service.MltwoLevelService;
import models.service.NewsService;
import models.service.UsersService;
import models.vo.query.CommoditysQuery;
import models.vo.query.IntroducesQuery;
import models.vo.query.MloneLevelQuery;
import models.vo.query.MltwoLevelQuery;
import models.vo.query.NewsQuery;
import models.vo.query.UsersQuery;
import play.cache.Cache;
import play.data.Upload;
import play.libs.Files;
import play.mvc.Before;
import play.mvc.Controller;
import common.*;
import common.JsonFile.jsonUtil;
public class manage extends Controller{
	
	
	public static String NAME;
	//图片的全局路径
	public static String IMG_PATH;

	public static MloneLevelService mloneLevelService;
	public static MltwoLevelService mltwolevelService;
	public static UsersService  usersService;
	public static CommoditysService  commoditysService;
	public static IntroducesService  introducesService;
	public static NewsService  newsService;
	
	public static String UPYUNPATH="testImg";//又拍云图片路径
	public static String COMPANYPATH;//公司信息json文件路径
	public static String LUNBOPATH;//轮播信息json文件路径
	public static String PPYSPATH;//品牌优势json文件路径
	public static String COMMODITYPATH;//首页商品json文件路径
	
	
	
	static {
		IMG_PATH = "http://industrial.b0.upaiyun.com";
		mloneLevelService = (MloneLevelService) play.modules.spring.Spring.getBean("mloneLevelService");
		mltwolevelService = (MltwoLevelService) play.modules.spring.Spring.getBean("mltwoLevelService");
		usersService = (UsersService)play.modules.spring.Spring.getBean("usersService");
		commoditysService = (CommoditysService)play.modules.spring.Spring.getBean("commoditysService");
		introducesService = (IntroducesService)play.modules.spring.Spring.getBean("introducesService");
		newsService = (NewsService)play.modules.spring.Spring.getBean("newsService");
		COMPANYPATH=System.getProperty("user.dir")+"/public/datas/companyInfo.json";
		PPYSPATH=System.getProperty("user.dir")+"/public/datas/companyInfo.json";
		LUNBOPATH=System.getProperty("user.dir")+"/public/datas/LUNBOInfo.json";
		COMMODITYPATH=System.getProperty("user.dir")+"/public/datas/communityInfo.json";
	}
	
	
	// #####################################信息展示################################################
	/**
	 * 一级目录信息
	 * @param name
	 */
	public static void MLOne() {
		MloneLevelQuery query = new MloneLevelQuery();
		Page page = mloneLevelService.findPage(query);
		render(page);
    }
	/**
	 * 二级目录信息
	 * @param name
	 */
	public static void MLTwo() {
		MltwoLevelQuery query = new MltwoLevelQuery();
		MloneLevelQuery Onequery = new MloneLevelQuery();
		Page Onepage = mloneLevelService.findPage(Onequery);
		Page page = mltwolevelService.findPage(query);
		render(page,Onepage);
    }
	/**
	 * 
	 * 获取商品页面
	 * 
	 */
	public static void commoditys() {
		
		MltwoLevelQuery mltwoLevelQuery = new MltwoLevelQuery();
		CommoditysQuery query = new CommoditysQuery();
		Page page = commoditysService.findPage(query);
		Page mltwoLevelpage = mltwolevelService.findPage(mltwoLevelQuery);
		
		render(page,mltwoLevelpage);
	}
	
	
	/**
	 * 
	 * 获取新闻页面
	 * 
	 */
	public static void news() {
		
		NewsQuery query = new NewsQuery();
		Page page = newsService.findPage(query);
		
		
		render(page);
	}

	
	// ##################################修改或新增信息#############################################
	/**
	 * 添加或修改一级目录
	 * @param id
	 * @param name
	 * @param state
	 */
	public static void updateOrAddMLOne(MloneLevelQuery oneQuery) {
		boolean flag=false;
		MloneLevel entity=new MloneLevel();
		if(null!=oneQuery){
			if(null!=oneQuery.getId()) {
				entity.setId(oneQuery.getId());
			}
			entity.setName(oneQuery.getName());
			entity.setEnable(oneQuery.getEnable());
			mloneLevelService.saveOrUpdate(entity);
		};
		
		renderText(flag);
	}
	/**
	 * 添加或修改二级目录
	 * @param id
	 * @param name
	 * @param state
	 */
	public static void updateOrAddMLTow(MltwoLevelQuery twoQuery) {
		boolean flag=false;
		MltwoLevel entity=new MltwoLevel();
		if(null!=twoQuery){
			if(null	!=twoQuery.getId()) {
				entity.setId(twoQuery.getId());
			}
			entity.setName(twoQuery.getName());
			entity.setEnable(twoQuery.getEnable());
			entity.setOneLevelId(twoQuery.getOneLevelId());
			mltwolevelService.saveOrUpdate(entity);
			flag=true;
		}
		renderText(flag);
	}
	
	
	/**
	 * 添加或修改商品
	 * @param id
	 * @param name
	 * @param state
	 */
	
	
	public static void updateOrAddCommoditys(Commoditys commoditys,String content) {
		commoditysService.saveOrUpdate(commoditys);
		renderJSON("{}");
	}
	
	/**
	 * 添加或修改新闻
	 * @param id
	 * @param name
	 * @param state
	 */
	
	
	public static void updateOrAddNews(News news) {
		newsService.saveOrUpdate(news);
		renderJSON("{}");
	}
	
	/**
	 * 添加或修改品牌优势
	 * @param id
	 * @param name
	 * @param state
	 */
	
	
	public static void updateOrAddIntroduces(Introduces introduces) {
		introducesService.saveOrUpdate(introduces);
		renderJSON("{}");
	}
	
	

	// #####################################删除信息################################################
	/**
	 * 删除一级目录(删除一级目录会删除二级目录 及二级目录所属商品)
	 * @param id
	 */
	public static void deleteOneById(int id) {
		boolean flag=false;
		if(0!=id) {
			MltwoLevelQuery query=new MltwoLevelQuery();
			query.setOneLevelId(id);
			Page<MltwoLevel> findPage = mltwolevelService.findPage(query);
			if(null!=findPage&&findPage.getResult().size()>0){
				for (MltwoLevel mltwoLevel : findPage) {
					commoditysService.deleteByMLTwoId(mltwoLevel.getId());//删除二级目录所属商品 根据二级目录id
				}
			}
			mltwolevelService.deleteByMLOneId(id);//删除二级目录根据一级目录id
			mloneLevelService.removeById(id);//删除一级目录
			flag=true;
		}
		renderText(flag);
	}
	/**
	 * 删除二级目录(删除二级目录 及二级目录所属商品)
	 * @param id
	 */
	public static void deleteTwoById(int id) {
		boolean flag=false;
		if(0!=id) {
			commoditysService.deleteByMLTwoId(id);//删除二级目录所属商品 根据二级目录id
			mltwolevelService.removeById(id);//删除二级目录所属商品
			flag=true;
		}
		renderText(flag);
	}
	
	
	/**
	 * 删除商品
	 * @param id
	 */
	public static void deleteCommById(int id) {
		boolean flag=false;
		if(0!=id) {
			commoditysService.removeById(id);//删除二级目录所属商品
			flag=true;
		}
		renderText(flag);
	}
	
	/**
	 * 删除品牌优势
	 * @param id
	 */
	public static void deleteIntrById(int id) {
		boolean flag=false;
		if(0!=id) {
			introducesService.removeById(id);
			flag=true;
		}
		renderText(flag);
	}
	
	
	// #######################################其他################################################## 
	/**
	 * login 登陆页面
	 */
	public static void login() {
        render();
    }
	
	
	
	/**
	 * login 登陆验证
	 * @param name
	 * @param pwd
	 */
	public static void loginYZ(String name ,String pwd) {
		boolean flag=false;
		if(null!=name&&name.trim().length()>0&&
				null!=pwd&&pwd.trim().length()>0
				) {
			
			UsersQuery query=new UsersQuery();
			query.setName(name);
			query.setPwd(pwd);
			
			Page page = usersService.findPage(query);
			List<Users> result = page.getResult();
			if(null != result && result.size()>0) {
				Users users = result.get(0);
				if(null!=users&&users.getName().trim().equals(name.trim()
						)&&users.getPwd().trim().equals(pwd.trim())) {
					flag=true;
					Cache.set(session.getId()+"users", users);
					renderJSON(flag);
				}
			}
			
		}
		
		renderText(flag);
    }
	
	

	// #######################################文件################################################## 
	
	public static void upload(File file) throws JSONException{
		List<Upload> files=(List<Upload>) request.args.get("__UPLOADS");
		boolean flag=false;
		 for (Upload upload : files) {
	            if (upload.getSize() > 0) {
	                File f = upload.asFile();
	                try {
	                	flag = ImageAction.upload(f, UPYUNPATH);
					} catch (Exception e) {
						e.printStackTrace();
					}
	            }
	        }
		 
		 
		renderJSON(flag);
	}
	
	
	
	/**
	 * 文件上传代码
	 * @throws JSONException 
	 */
	public static void upfile() throws JSONException {
	
		
		List<String> list = getFiles();
		render(list);
	}
	
	
	/**
	 * 
	 * 弹出的框，上传和选择文件
	 * 
	 */
	public static void upFileT(int maxIndex) {
		

		List<String> list = getFiles();
		
		render(list,maxIndex);
	}
	
	
	/**
	 * 获取U盘云的文件
	 */
	
	public static List<String> getFiles() {
		
		
		List<String> list=new ArrayList<String>();
		String readFile = ImageAction.readFile();
		String[] split = readFile.split("\n");
		if(!readFile.isEmpty()){
			for (int i = 0; i < (split.length>10?10:split.length); i++) {
				list.add("/testImg/"+split[i].substring(0, split[i].indexOf("N")).trim());
			}
		}
		
		return list;
		
	}
	
	
	/**
	 * 登陆的后台首页
	 */
	public static void  index() {
		
		render();
	}
	/**
	 * 首页管理
	 */
	public static void indexManage(){
		
		render();
	}
	
	
	/**
	 * 添加或修改商品页面
	 * @param id
	 */
	public static void addOrUpCommoditys(Integer id) {
		
		MltwoLevelQuery mltwoLevelQuery = new MltwoLevelQuery();
		CommoditysQuery query = new CommoditysQuery();
		Page mltwoLevelpage = mltwolevelService.findPage(mltwoLevelQuery);
		String img_path = IMG_PATH;
		if(id!=-1) {
			query.setId(id);
			Commoditys object = (Commoditys)commoditysService.findPage(query).getResult().get(0);
			if(null != object.getImg()) {
				String[] split = object.getImg().split("\\*\\*\\*\\*");
				render(object,mltwoLevelpage,split,img_path);
			}
		
			object = new Commoditys();
			render(object,mltwoLevelpage,img_path);
		}
	
		Commoditys object = new Commoditys();

		render(object,mltwoLevelpage,img_path);
		

	}
	
	/**
	 * 添加或修改新闻页面
	 * @param id
	 */
	public static void addOrUpNews(Integer id) {
		
		
		NewsQuery query = new NewsQuery();
		
		if(id!=-1) {
			query.setId(id);
			News object = (News)newsService.findPage(query).getResult().get(0);
			String img_path = IMG_PATH;
			render(object,img_path);
		}
	
		News object = new News();
		String img_path = IMG_PATH;
		render(object,img_path);
		

	}
	
	
	/**
	 * 添加或修改品牌优势页面
	 * @param id
	 */
	public static void addOrUpIntroduces(Integer id) {
		
		IntroducesQuery query = new IntroducesQuery();

		if(id!=-1) {
			query.setId(id);
			Introduces object = (Introduces)introducesService.findPage(query).getResult().get(0);
			String img_path = IMG_PATH;
			render(object,img_path);
		}
	
		Introduces object = new Introduces();
		
	
		String img_path = IMG_PATH;
		render(object,img_path);
		

	}
	
	//##############################################公司管理########################################################
	/**
	 * 公司管理
	 */
	public static void companyManage(){
		//读取公司信息
		String companyJson = common.JsonFile.jsonUtil.ReadFile(COMPANYPATH);
		JSONObject companyInfo=JSONObject.parseObject(companyJson);
		//读取品牌信息
		//读取轮播信息
		String LUBBOJson = common.JsonFile.jsonUtil.ReadFile(LUNBOPATH);
		JSONObject LunBOInfo=JSONObject.parseObject(LUBBOJson);
		//读取商品信息
		
		IntroducesQuery query = new IntroducesQuery();
		List result = introducesService.findPage(query).getResult();
		
		String img_path = IMG_PATH;
		render(companyInfo,LunBOInfo,result,img_path);
	}

	/**
	 * 公司信息修改
	 */
	public static void companyUp(String logoimg,String companyName,String companyDetail,String companyTelephone,String companyEmail){
		try {
		//读取公司信息  还差图片处理
			String JsonContext = common.JsonFile.jsonUtil.ReadFile(COMPANYPATH);
			JSONObject companyInfo=JSONObject.parseObject(JsonContext);
			
//			if(!comimg.isEmpty()){
//				companyInfo.put("companyImg",comimg);
//			}
			if(!logoimg.isEmpty()){
				companyInfo.put("companyWximg",IMG_PATH+logoimg);
			}
			if(!companyName.isEmpty()){
				companyInfo.put("companyName",companyName);
			}
			if(!companyDetail.isEmpty()){
				companyInfo.put("companyDetail",companyDetail);
			}
			if(!companyTelephone.isEmpty()){
				companyInfo.put("companyTelephone",companyTelephone);
			}
			if(!companyEmail.isEmpty()){
				companyInfo.put("companyEmail",companyEmail);
			}
			
			
			
			jsonUtil.writeFile(COMPANYPATH, companyInfo.toString());
			renderJSON(true);
		} catch (IOException e) {
			e.printStackTrace();
		};
		renderJSON(false);
	}
	
	/*
	*//**
	 * 轮播修改或添加
	 */
	public static void LUNBOAddOrUp( String index,String img){
		try {			
			if(!index.isEmpty()) {
				
				jsonUtil.writeFile(LUNBOPATH, index.toString());
				renderJSON(true);
			}
			
			renderJSON(true);
		} catch (Exception e) {
			e.printStackTrace();
		};
		renderJSON(false);
	}
	
	
	public static void delUPYImg(String img) {
		try {
			ImageAction.testDeleteFile(img);
			renderJSON(true);
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		renderJSON(false);
	}
	
	@Before(unless= {"login","loginYZ"})
	public static void init() {
		Object object = Cache.get(session.getId()+"users");
		if(null==object||"".equals(object)) {
			redirect("/login");	
		}
		
	}
}
